package com.cars.util.sign;

import java.io.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

/**
 * @description: 数字签名工具类
 * @author: 孔垂云
 * @version: 1.0
 * @date: 2020/4/16 13:52
 */
public class SignUtil {
    //私钥和公钥地址
    public static String privateKeyPath = "/weblogic/key/hy_private.key";
    public static String publicKeyPath = "/weblogic/key/hy_public.key";

    /**
     * 私钥
     */
    private static RSAPrivateKey privateKey;

    /**
     * 公钥
     */
    private static RSAPublicKey publicKey;

    static {
        try {
            privateKey = (RSAPrivateKey) readObject(privateKeyPath);
            publicKey = (RSAPublicKey) readObject(publicKeyPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 签名
     *
     * @param stringA 待签名字符串
     * @return
     */
    public static String sign(String stringA) {
        RsaEncrypt rsaEncrypt = new RsaEncrypt();
        byte[] sign = rsaEncrypt.rsaSign(stringA, privateKey);
        String signStr = Base64Util.encode(sign);
        return signStr;
    }

    /**
     * 验签
     *
     * @param stringA 验签字符串
     * @param sign    签名值
     * @return
     */
    public static boolean verify(String stringA, String sign) {
        RsaEncrypt rsaEncrypt = new RsaEncrypt();
        boolean flag = rsaEncrypt.verify(stringA, Base64Util.decodeToByte(sign), publicKey);
        return flag;
    }

    public static void writeObject(String path, Object map) {
        try {
            File f = new File(path);
            FileOutputStream out = new FileOutputStream(f);
            ObjectOutputStream objwrite = new ObjectOutputStream(out);
            objwrite.writeObject(map);
            objwrite.flush();
            objwrite.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Object readObject(String path) {
        Object map = null;
        try {
            FileInputStream in = new FileInputStream(path);
            ObjectInputStream objread = new ObjectInputStream(in);
            map = objread.readObject();
            objread.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }


}
